import { pathToRegexp } from "path-to-regexp";

// /pages/journal-detail/journal-detail?id=80&mid=113&uid=1&origin=friend

const whiteList = [
  "(.*)/pages/login/login",
  "(.*)/pages/register/register",
  "(.*)/pages/index/index",
  "(.*)/",
  "(.*)/pages/login/login\\?redirect=(.*)",
  "(.*)/pages/friend/friend\\?id=(.*)",
  "(.*)/pages/friend/friend",
  "(.*)/pages/modify-password/modify-password",
  // "(.*)/pages/journal-detail/journal-detail(.*)",
];

// /^\/pages\/friend\/friend\?redirect=/
const list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];

import { useUserStore } from "./stores/useUserStore";

list.forEach((item) => {
  uni.addInterceptor(item, {
    invoke(args) {
      const { url } = args;
      // console.log(
      //   pathToRegexp("/pages/login/login?redirect=/pages/friend/friend?id=1")
      // );
      if (!isMatch(url)) {
        const { userInfo } = useUserStore();
        if (!userInfo) {
          // 添加登录页面到页面栈
          uni.navigateTo({
            url: "/pages/login/login",
          });
          return false;
        } else {
          return true;
        }
      } else {
        return true;
      }
    },
    fail(err) {
      console.log(err);
    },
  });
});

function isMatch(url: string) {
  return whiteList.some((item) => {
    const reg = pathToRegexp(item);
    return reg.test(url);
  });
}
